﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.UI.Models;
using SCMS.Model;
using SCMS.CoreBusinessLogic.TenderAnalysis;
using SCMS.CoreBusinessLogic.WRF;
using SCMS.UI.GeneralHelper;
using System.Collections;
using SCMS.CoreBusinessLogic.ActionFilters;
using SCMS.CoreBusinessLogic.Web;
using SCMS.CoreBusinessLogic.Security;
using System.Text;
using SCMS.CoreBusinessLogic.NotificationsManager;
using SCMS.CoreBusinessLogic.StaffServices;
using SCMS.CoreBusinessLogic.WB;

namespace SCMS.UI.Controllers
{
    [MyException]
    public class WRFormController : PortalBaseController
    {

        private ITAnalysisService TAService;
        private IWareHouseReleaseService WRFservice;
        private INotificationService notificationService;
        private readonly IStaffService staffService;
        private IWayBillService WBservice;

        public WRFormController(IPermissionService permissionService, IUserContext userContext, ITAnalysisService TAService, IWareHouseReleaseService WRFservice,
            INotificationService notificationService, IStaffService staffService, IWayBillService WBservice)
            : base(userContext, permissionService)
        {
            this.TAService = TAService;
            this.WRFservice = WRFservice;
            this.notificationService = notificationService;
            this.staffService = staffService;
            this.WBservice = WBservice;
        }
        //
        // GET: /WRForm/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult LoadWRF()
        {
            return LoadWR();
        }

        private ActionResult LoadWR(Guid? wrnId = null)
        {

            var model = new WRFRequest();
            if (wrnId == null)
            {
                freshview(model);
            }
            else
            {
                using (var db = new SCMSEntities())
                {
                    Model.WarehouseRelease wrn = db.WarehouseReleases.FirstOrDefault(p => p.Id == wrnId);
                    if (wrn != null)
                    {
                        model.EntityWHouseRelease = wrn;
                        model.WRNItemList = WRFservice.GetWRNItems(wrn.Id);
                    }
                    else freshview(model);
                }
            }
            model.Staff = new SelectList(TAService.GetStaffs(countryProg.Id), "StaffID", "StaffName");
            model.Warehouses = new SelectList(WBservice.GetWarehouses(countryProg.Id), "Id", "Name");
            model.ApproversList = new SelectList(staffService.GetStaffByApprovalDoc(NotificationHelper.wrnCode, countryProg.Id), "Id", "StaffName");
            model.EntityWHouseRelease.ReceivedBy = currentStaff.Id;
            ViewBag.RequestorName = currentStaff.Person.FirstName + " " + currentStaff.Person.OtherNames;
            return View("LoadWRF", model);
        }

        private void freshview(WRFRequest model)
        {
            model.EntityWHouseRelease = new WarehouseRelease();
            model.EntityWHouseRelease.RefNumber = "--NEW WRO--";
            model.EntityWHouseRelease.RequestDate = DateTime.Today;
            model.WRNItemList = new List<WarehouseReleaseItem>();
        }

        public ActionResult LoadWRFItem(WRFRequest WRNmodel)
        {
            WRNmodel.EntityWHouseRelease.Id = Guid.NewGuid();
            WRNmodel.EntityWHouseRelease.NotReleased = true;
            WRNmodel.EntityWHouseRelease.CountryProgrammeId = countryProg.Id;
            WRNmodel.EntityWHouseRelease.PreparedOn = DateTime.Now;
            WRNmodel.EntityWHouseRelease.PreparedBy = currentStaff.Id;
            UserSession.CurrentSession.NewWRN = WRNmodel.EntityWHouseRelease;
            return NewItem(WRNmodel.EntityWHouseRelease.Id);
        }

        public ActionResult NewItem(Guid wrnId)
        {
            Guid warehouseId;
            if (UserSession.CurrentSession.NewWRN != null) warehouseId = UserSession.CurrentSession.NewWRN.WareHouseId;
            else warehouseId = WRFservice.GetWROById(wrnId).WareHouseId;

            var model = new WRForm()
                {
                    EntityWhouseRItem = new WarehouseReleaseItem(),
                    Items = new SelectList(WRFservice.GetInventoryItems(countryProg.Id, warehouseId), "Id", "Name")
                };

            ViewBag.WRNId = wrnId;
            return View("LoadWRFItem", model);
        }

        public ActionResult GetAssets(Guid id)
        {
            StringBuilder blineOption = new StringBuilder();
            using (var db = new SCMSEntities())
            {
                if (db.Inventories.FirstOrDefault(p => p.Id == id).Item.ItemCategory.CategoryCode == "C")
                {
                    blineOption.Append("<input data-val=\"true\" data-val-number=\"The field Quantity must be a number.\" id=\"txtqtyordered\" name=\"EntityWhouseRItem.Quantity\" type=\"text\" value=\"0\" />");
                    blineOption.Append("<span class=\"field-validation-valid\" data-valmsg-for=\"EntityWhouseRItem.Quantity\" data-valmsg-replace=\"true\"></span>");
                }
                else
                {
                    blineOption.Append("<select id=\"dplassetId\" name=\"EntityWhouseRItem.AssetId\"><option value=\"\">- please select -</option>");
                    List<Model.Asset> BLines = WRFservice.GetAssets(id);
                    foreach (Asset item in BLines)
                        blineOption.Append("<option value=\"" + item.Id + "\">" + item.Name + "</option>");
                    blineOption.Append("</select>");
                    blineOption.Append("<span class=\"field-validation-valid\" data-valmsg-for=\"EntityWhouseRItem.AssetId\" data-valmsg-replace=\"true\"></span>");

                    blineOption.Append("<input type=\"hidden\" id=\"txtqtyordered\" value=\"0\" />");
                }
            }
            ViewBag.Html = blineOption.ToString();
            return View("HTMLResponses");
        }

        public ActionResult SaveWRN(Guid id, WRForm entitymodel)
        {
            entitymodel.EntityWhouseRItem.WarehouseReleaseId = id;
            if (WRFservice.SaveWRF(UserSession.CurrentSession.NewWRN, entitymodel.EntityWhouseRItem))
            {
                ViewBag.Response = 1;
                ViewBag.msg = "Item added successfully";
                UserSession.CurrentSession.NewWRN = null;
                ModelState.Clear();
            }
            else { ViewBag.Response = 0; ViewBag.msg = "An error has occurred"; }
            return LoadWRItems(id);
        }

        public ActionResult LoadWRItems(Guid id)
        {
            return LoadWR(id);
            //Models.WRNItems WRItem; ViewBag.WRNId = id;
            //List<WarehouseReleaseItem> wrnList = WRFservice.GetWRNItems(id);
            //List<WRNItems> WRItemz = new List<WRNItems>();
            //foreach (WarehouseReleaseItem bc in wrnList)
            //{
            //    WRItem = new WRNItems();
            //    WRItem.EntityWhouseRItem = bc;
            //    WRItemz.Add(WRItem);
            //}
            //return View(WRItemz);
        }

        public ActionResult DeleteWRNItem(Guid wrnId, Guid wrnItmId)
        {
            if (!WRFservice.IsWRNItemDeleted(wrnItmId))
            { ViewBag.Response = 0; ViewBag.msg = "An error has occurred"; return LoadWR(wrnId); }
            ViewBag.Response = 1;
            ViewBag.msg = "Item deleted successfully";
            return LoadWR(wrnId);
        }

        public ActionResult IsQtyenough(Models.CheckAvailableQty bc)
        {
            using (var db = new SCMSEntities())
            {
                if (bc.assetid != null)
                    if (db.Assets.FirstOrDefault(p => p.Id == bc.assetid).IsReleased)
                    {
                        ViewBag.Html = "0~ This asset is already released"; return View("HTMLResponses");
                    }

                Model.Inventory entity = db.Inventories.First(p => p.Id == bc.InventoryId);
                ViewBag.Html = bc.releasedQty <= entity.Quantity ? "1" : "0~ There only " + (Int64)entity.Quantity + " " + entity.Item.Name + " (s) left in stock";
                return View("HTMLResponses");
            }
        }

        public ActionResult DeleteWRO(Guid id)
        {
            List<WarehouseReleaseItem> wroItems = WRFservice.GetWRNItems(id);
            foreach (var wroItem in wroItems)
            {
                WRFservice.DeleteWarehouseReleaseItemById(wroItem.Id);
            }
            WRFservice.DeleteWarehouseReleaseById(id);
            return viewWRN();
        }

        public ActionResult SubmitWRN(Guid id)
        {
            WarehouseRelease wrn = WRFservice.GetWROById(id);
            wrn.PreparedOn = DateTime.Now;
            wrn.IsApproved = false;
            wrn.IsSubmitted = true;
            wrn.RefNumber = WRFservice.GenerateUniquNumber(countryProg);
            WRFservice.SaveApproved(wrn);
            //Send notification
            notificationService.SendToAppropriateApprover(NotificationHelper.wrnCode, NotificationHelper.approvalCode, wrn.Id);
            return viewWRN();
        }

        public ActionResult viewWRN()
        {
            Models.ViewWRNs WRN;
            List<WarehouseRelease> wrnList = WRFservice.GetWRNs(countryProg.Id);
            List<ViewWRNs> WRItemz = new List<ViewWRNs>();
            foreach (WarehouseRelease wrn in wrnList)
            {
                WRN = new ViewWRNs();
                WRN.EntityWHouseRelease = wrn;
                WRN.Requestor = WRFservice.GetStaffName(wrn.PreparedBy);
                WRN.Recipient = WRFservice.GetStaffName((Guid)wrn.ReceivedBy);
                WRItemz.Add(WRN);
            }
            return View("viewWRN", WRItemz);
        }

        public ActionResult ViewNRNDetails(Guid id)
        {
            using (var db = new SCMSEntities())
            {
                WarehouseRelease wrnenttiy = db.WarehouseReleases.First(p => p.Id == id);
                List<Model.WarehouseReleaseItem> writms = wrnenttiy.WarehouseReleaseItems.ToList();
                foreach (WarehouseReleaseItem item in writms)
                {
                    Model.Inventory a = item.Inventory;
                    Model.Item i = a.Item;
                    Model.ItemCategory ic = i.ItemCategory;
                    Model.Asset ast = item.Asset;
                    Model.UnitOfMeasure u = a.Item.UnitOfMeasure;
                }
                //Dummies
                if (wrnenttiy.Staff != null)
                {
                    var person = wrnenttiy.Staff.Person;
                    var desg = wrnenttiy.Staff.Designation;
                    var office = wrnenttiy.Staff.CountrySubOffice;
                }
                if (wrnenttiy.Staff1 != null)
                {
                    var person = wrnenttiy.Staff1.Person;
                    var desg = wrnenttiy.Staff1.Designation;
                    var office = wrnenttiy.Staff1.CountrySubOffice;
                }
                if (wrnenttiy.Staff2 != null)
                {
                    var person = wrnenttiy.Staff2.Person;
                    var desg = wrnenttiy.Staff2.Designation;
                    var office = wrnenttiy.Staff2.CountrySubOffice;
                }
                var model = new ViewWRNDetails()
                {
                    EntityWHouseRelease = wrnenttiy,
                    writems = writms,
                    Requestor = db.VStaffDetails.First(p => p.StaffID == wrnenttiy.PreparedBy),
                    Recipient = db.VStaffDetails.First(p => p.StaffID == wrnenttiy.ReceivedBy)
                };

                //Manage approval link
                string actionType = null;
                if (model.EntityWHouseRelease.IsSubmitted && !model.EntityWHouseRelease.IsApproved && !model.EntityWHouseRelease.IsRejected)
                    actionType = NotificationHelper.approvalCode;
                if (actionType != null)
                    model.CanApprove = notificationService.CanApprove(currentUser, NotificationHelper.wrnCode, actionType, model.EntityWHouseRelease.Id);
                else
                    model.CanApprove = false;

                return View("ViewNRNDetails", model);
            }
        }
    }
}
